﻿using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;

namespace ConfExpert.Forms.ImportWizards
{
    public partial class DikilenGomlekler : XImportWizard
    {
        public DikilenGomlekler()
        {
            InitializeComponent();

            A = "(A) Sistemdeki Sipariş Adedi";
            B = "(B) Dosyadaki Kesilen Adet";
            C = "(C) Fazla Kesim";
            D = "(D) Sistemdeki Kesilen Adet";

            Init("Dikilen Gömlek Dosyası", false);
            this.FileDone += DikilenGomlekler_FileDone;
            btnSave.ItemClick += BtnSave_ItemClick;
        }

        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SourceTable.Columns.Remove("Tip");
            string xml = SourceTable.Serialize();
            ExecuteNonQuery("UpdDikilen", xml);
            MasterGrid.Init(new DataTable());
            ShowMessage("Kayıtlar başarıyla güncellendi.");
        }

        DataTable SourceTable = new DataTable();
        string A;
        string B;
        string C;
        string D;

        private void DikilenGomlekler_FileDone(DataSet ds, string FileName)
        {
            DataTable dtResult = new DataTable();

            DataSet dsResult = new DataSet();
            dsResult.Tables.Add(dtResult);

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];
                DataTable dtSheet = ProcessSheet(dt);

                //dtSheet.Columns.Add("Toplam", typeof(string));
                dtSheet.Columns.Add("SheetName", typeof(string));
                dtSheet.Columns.Add("FileName", typeof(string));

                foreach (DataRow dr in dtSheet.Rows)
                {
                    dr["SheetName"] = dt.TableName;
                    dr["FileName"] = FileName;  //*
                }

                dtResult.Merge(dtSheet);
            }

            dtResult.DefaultView.Sort = "PlanlamaLinesId,Tip";
            SourceTable = dtResult.Select("Tip='" + B + "'").CopyToDataTable();

            MasterGrid.Init(dtResult.DefaultView.ToTable());
            MasterGrid.YanYanaGetir("Toplam:FileName");

            MasterGrid.AddSummary();
            MasterGrid.MakeReadOnly();
            MasterGrid.Columns["PlanlamaLinesId"].Group();
            MasterGrid.ExpandAllGroups();

            MasterGrid.BestFitColumns();
            MasterGrid.Columns["Tip"].Width = MasterGrid.Columns["Tip"].Width + 30;

            gvMaster.OptionsView.EnableAppearanceEvenRow = false;
            gvMaster.MakeRowSelectable();

            GridManager gm = GridManager.GetManager(MasterGrid);
            gm.Utility.SadeceDoluSutunlariGoster(true);

            gvMaster.MakeColumnInvisible("SheetName");
            gvMaster.Columns["Toplam"].Width = 70;
        }

        private DataTable ProcessSheet(DataTable dt)
        {
            DataRow drFirst = dt.Rows[0];
            int BedenBaslangic = -1;
            int BedenBitis = -1;
            int PLinesIdIndex = -1;
            int PDagilimIdIndex = -1;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string colName = drFirst[i].ToStr().ToLower();
                if (colName == "PLinesId".ToLower())
                    PLinesIdIndex = i;
                else if (colName == "PDagilimId".ToLower())
                    PDagilimIdIndex = i;
                else if (colName == "Tip".ToLower())
                    BedenBaslangic = i + 1;
                else if (colName == "Toplam Adet".ToLower())
                    BedenBitis = i - 1;
            }

            int TipIndex = BedenBaslangic - 1;

            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("PlanlamaLinesId", typeof(int));
            dtResult.Columns.Add("PlanlamaDagilimId", typeof(int));
            dtResult.Columns.Add("Tip", typeof(string));

            DataTable dtDagilim = Session.DataManager.ExecuteDataTableByQuery("select Name, Beden from dagilimVertical d inner join planlama p on d.dagilimId = p.DagilimId inner join PlanlamaLines pl on p.PlanlamaId = pl.PlanlamaId where pl.PlanlamaLinesId = " + dt.Rows[1][PLinesIdIndex].ToString());
            List<string> ListTemp = new List<string>();

            int revBitis = BedenBitis;

            for (int i = BedenBaslangic; i < BedenBitis + 1; i++)
            {
                string nameInFile = drFirst[i].ToStr();
                if (nameInFile == "")
                {
                    revBitis = i - 1;
                    break; ;
                }
                DataColumn dc = new DataColumn();
                dc.DataType = typeof(int);

                string orjColName = dtDagilim.Select("Beden='" + nameInFile + "'")[0]["Name"].ToStr();

                dc.Caption = nameInFile;
                dc.ColumnName = orjColName;
                ListTemp.Add(orjColName);
                dtResult.Columns.Add(dc);
            }
            BedenBitis = revBitis;

            string strCols = "case Sipkes when 1 then '" + A + "' when 2 then '" + D + "' end Tip, PlanlamaLinesId, PlanlamaDagilimId," + String.Join(",", ListTemp.ToArray());

            ListTemp = new List<string>();
            if (drFirst[0].ToStr() == "PLinesId" && drFirst[1].ToStr() == "PDagilimId")
            {
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    string tip = dr[TipIndex].ToStr().ToLower();
                    if (tip == "kes")
                    {
                        DataRow drNew = dtResult.NewRow();
                        drNew["PlanlamaLinesId"] = dr[PLinesIdIndex].ToInt(-1);
                        drNew["PlanlamaDagilimId"] = dr[PDagilimIdIndex].ToInt(-1);
                        drNew["Tip"] = B;

                        for (int colIndex = BedenBaslangic; colIndex < BedenBitis + 1; colIndex++)
                        {
                            string colName = ("A" + (colIndex - BedenBaslangic + 1).ToString().PadLeft(2, '0'));
                            int total = dr[colIndex].ToInt();
                            if (total > 0)
                            {
                                drNew[colName] = total;
                                //drNew["Toplam"] = drNew["Toplam"].ToInt() + total;
                            }
                        }
                        ListTemp.Add(dr[PLinesIdIndex].ToString());
                        dtResult.Rows.Add(drNew);
                    }
                }
                string sql = "select " + strCols + " from PlanlamaDagilim where sipkes in (1,2) and PlanlamaLinesId in (" + String.Join(",", ListTemp.ToArray()) + ")";
                DataTable dtOrj = Session.DataManager.ExecuteDataTableByQuery(sql);                
                dtResult.Merge(dtOrj);

                List<string> exp = new List<string>();
                for (int c = 1; c <= 28; c++)
                    if (dtOrj.Columns.Contains("A" + c.ToString().PadLeft(2, '0')))
                        exp.Add("ISNULL(A" + c.ToString().PadLeft(2, '0') + ",0)");
                dtResult.Columns.Add("Toplam", typeof(int), string.Join("+", exp.ToArray()));

                DataTable dtFark = dtResult.Clone();
                foreach (DataRow dr in dtResult.DefaultView.ToTable(true, "PlanlamaLinesId").Rows)
                {
                    string PlanlamaLinesId = dr["PlanlamaLinesId"].ToString();
                    DataRow[] sip = dtResult.Select(string.Format("Tip='{0}' and PlanlamaLinesId={1}", A, PlanlamaLinesId));
                    DataRow[] kes = dtResult.Select(string.Format("Tip='{0}' and PlanlamaLinesId={1}", B, PlanlamaLinesId));

                    string ignores = "PlanlamaLinesId,PlanlamaDagilimId,Tip,SheetName,FileName";
                    DataRow drNew = dtFark.NewRow();
                    for (int i = 0; i < dtResult.Columns.Count; i++)
                    {
                        DataColumn dc = dtResult.Columns[i];
                        if (!ignores.Contains(dc.ColumnName))
                        {
                            int fark = kes[0][dc.ColumnName].ToInt(-1) - sip[0][dc.ColumnName].ToInt(-1);
                            if (fark != 0)
                                drNew[dc.ColumnName] = fark;
                        }
                    }
                    drNew["Tip"] = C;
                    drNew["PlanlamaLinesId"] = PlanlamaLinesId.ToInt(-1);
                    dtFark.Rows.Add(drNew);
                    // int p1 = (int) dtResult.Select("PlanlamaLinesId=" + dr["PlanlamaLinesId"].ToString() + " and Tip = ''")[0]["A01"];
                }

                dtResult.Merge(dtFark);
            }
            else
                ShowMessage("Hatalı dosya !");

            return dtResult;
        }

        private void gvMaster_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > 0)
                if (gvMaster.GetDataRow(e.RowHandle)["Tip"].ToString() == B)
                    e.Appearance.Font = new System.Drawing.Font(e.Appearance.Font, System.Drawing.FontStyle.Bold);
                else if (gvMaster.GetDataRow(e.RowHandle)["Tip"].ToString() == D)
                    e.Appearance.BackColor = System.Drawing.Color.SkyBlue;
        }

        private void DikilenGomlekler_Load(object sender, EventArgs e)
        {

        }
    }
}